package server;

import java.io.IOException;

import controller.XMLController;
import db.Manager;
import xml.Message;

public class ServerLauncher {

	/**
	 * Launches the server
	 * @param args
	 */
	final static int DEFAULT_PORT = 9371;
	
	public static void main(String[] args) {
		int port = DEFAULT_PORT;
		if(!Message.configure("draw2choose.xsd")){
			System.exit(0);
		}
		
		if(!Manager.connect()){
			System.out.println("Unable to connect to database");
			System.exit(0);
		}
		
		// Try to use first argument as the port
		if(args.length > 0){
			try{
				port = Integer.valueOf(args[0]);
			}catch(NumberFormatException e){
				System.out.println("Failed to parse port '"+args[0]+"', using default");
				port = DEFAULT_PORT;
			}
		}
		
		Server server = new Server(new XMLController(), port);
		
		try{
			server.bind();
		}catch(IOException e){
			System.err.println("Unable to launch server: "+e.getMessage());
			System.exit(-1);
		}

		System.out.println("Server awaiting client connections on port "+port);
		try {
			server.process();
			System.out.println("Server shutting down.");
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}    
	}

}
